package com.ruoyi.framework.app;

import com.ruoyi.common.app.JwtTokenUtil;
import com.ruoyi.common.wx.domain.WxUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//过滤器实现token校验，获取用户信息，用户信息放在HttpServletRequest 中传递给controller
@Component
public class AppAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    private static final List<String> noAuthUris = new ArrayList<String>() {{
        add("/app/loginByOpenId");
    }};

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        try {
            String requestURI = request.getRequestURI();
            // 检查请求的URL是否匹配特定地址
            if (requestURI.startsWith("/app/") && !noAuthUris.contains(request.getRequestURI())) {
                String token = String.valueOf(request.getHeader("token"));
                if (!jwtTokenUtil.validateToken(token)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "token不正确!");
                    return;
                }
                Map<String, Object> claims = jwtTokenUtil.parseToken(token);
                request.setAttribute("appUser", claims.get("appUser"));
                request.setAttribute("appUserId", claims.get("appUserId"));
            }
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "token不正确!");
            e.printStackTrace();
            return;
        }
        filterChain.doFilter(request, response);
    }

    private String getUsernameFromRequest(HttpServletRequest request) {
        String username = request.getHeader("X-App-Username");
        return username;
    }
}

